/**
 * 
 */
package fluo.rtp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Creates a UDP socket in a separate thread, and transmits data based on the file specified
 * CURRENTLY NOT WORKING
 * @author maherbeg
 *
 * Created: Apr 16, 2009
 * Modified: Apr 16, 2009
 */
public class RTPStream implements Runnable {

	private MP3Object tostream;
	private DatagramSocket socket;
	private int seq = 0;
	
	private String destip;
	private int destport;
	
	public boolean sending = false;
	
	public void run() {
		
		while(sending && seq<tostream.getSize()){
			int curtime = (int)(System.currentTimeMillis()&0xFFFFFFFF); //retrieve lower 32 bits of the system timer
			
			RTPpacket tosend = new RTPpacket(RTPpacket.PT_TYPE_MP3, seq, curtime, 
									tostream.getFrame(seq), tostream.getFrame(seq).length);
			
			seq++;
			
			byte payload[] = new byte[tosend.getlength()];
			tosend.getpacket(payload);
			
			DatagramPacket p = new DatagramPacket(payload, payload.length);
			try {
				p.setAddress(InetAddress.getByName(destip));
			} catch (UnknownHostException e1) {
				System.out.println("RTPStream.run(): Unknown host...how the hell did we get here? Exiting stream");
				e1.printStackTrace();
				return;
			}
			p.setPort(destport);
			
			try {
				socket.send(p);
			} catch (IOException e1) {
				System.out.println("RTPStream.run(): Error sending frame " + (seq-1) + "...skipping it");
				e1.printStackTrace();
			}
			
			
			try { //90khz timing
				Thread.sleep(0, (int)(1000*1000/90000.0*1000));
			} catch (InterruptedException e) {
				System.out.println("RTPStream.run(): Interrupted while waiting...");
				e.printStackTrace();
			}
		}
		
		socket.close();
		System.out.println("RTPStream.run(): Finished sending mp3 file");
		
	}

	public RTPStream(String file, String ip, int port){
		destip = ip;
		destport = port;
		
		try {
			tostream = new MP3Object(file);
		} catch (IOException e) {
			System.out.println("RTPStream.RTPStream(): Can not parse MP3 File, abandoning stream.");
			e.printStackTrace();
			return;
		}
		
		try {
			socket = new DatagramSocket();//port, InetAddress.getByName(ip));
			//successfully read the file, let's connect
			//socket.connect(InetAddress.getByName(ip), port);
		} catch (SocketException e) {
			System.out.println("RTPStream.RTPStream(): Error creating socket...abandoning stream.");
			e.printStackTrace();
			socket = null;
			tostream = null;
			return;
		}
		
		sending = true;
		Thread t= new Thread(this);
		t.start();
	}
	
	public static void main(String args[]){
		RTPStream rtp = new RTPStream("/Users/maherbeg/Music/iTunes/iTunes Music/Aesop Rock/Labor Days/01 Labor.mp3", 
									"localhost", 1234);
	}
}
